package com.sptpc.demo.service.impl;

import com.sptpc.demo.model.Category;
import com.sptpc.demo.model.Drink;
import com.sptpc.demo.repository.CategoryRepository;
import com.sptpc.demo.repository.DrinkRepository;
import com.sptpc.demo.service.IDrinkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

@Service
public class DrinkJpaService implements IDrinkService {
    @Autowired
    private DrinkRepository drinkRepository;
    @Autowired
    private CategoryRepository categoryRepository;

    @Override
    public Page<Drink> getAllDriks(PageRequest pageRequest) {

        return  drinkRepository.findAll(pageRequest);
    }

    @Override
    public void addNewDrink(Drink drink, Integer categoryId) {
        // 1. 通过categoryId查询category
        Category category = categoryRepository.findById(categoryId).orElse(null);

        // 2. 将category设置给drink
        drink.setCategory(category);

        drinkRepository.save(drink);

    }

    @Override
    public Drink getDrinkById(Integer id) {
        return drinkRepository.findById(id).orElse(null);
    }

    @Override
    public void updateDrink(Drink drink) {
        drinkRepository.save(drink);
    }

    @Override
    public void deleteDrinkById(Integer id) {
        drinkRepository.deleteById(id);
    }
}
